package factory.one.service;

import factory.one.entity.Money;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.List;

/**
 * @author sk.z
 * 2023/9/20
 * 收支
 **/
@Service
public class MoneyService {

    private final JdbcTemplate jdbcTemplate;

    public MoneyService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Long add(Money money) {
        PreparedStatementCreator psc = con -> {
            PreparedStatement ps = con.prepareStatement("insert into MONEY(order_id,type,content,amount,occur_time,create_user,create_time) values(?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
            ps.setLong(1, money.getOrderId());
            ps.setInt(2, money.getType());
            ps.setString(3, money.getContent());
            ps.setLong(4, money.getAmount());
            ps.setTimestamp(5, new Timestamp(money.getOccurTime().getTime()));
            ps.setString(6, money.getCreateUser());
            ps.setTimestamp(7, new Timestamp(money.getCreateTime().getTime()));
            return ps;
        };
        GeneratedKeyHolder holder = new GeneratedKeyHolder();
        jdbcTemplate.update(psc, holder);
        return holder.getKey() == null ? null : holder.getKey().longValue();
    }

    public List<Money> listByOrder(Long orderId) {
        return jdbcTemplate.query("select * from MONEY where order_id = ? order by id", new MoneyRowMapper(), orderId);
    }

    private static class MoneyRowMapper implements RowMapper<Money> {
        @Override
        public Money mapRow(ResultSet rs, int rowNum) throws SQLException {
            Money money = new Money();
            money.setId(rs.getLong("id"));
            money.setOrderId(rs.getLong("order_id"));
            money.setType(rs.getInt("type"));
            money.setContent(rs.getString("content"));
            money.setAmount(rs.getLong("amount"));
            money.setOccurTime(rs.getTimestamp("occur_time"));
            money.setCreateUser(rs.getString("create_user"));
            money.setCreateTime(rs.getTimestamp("create_time"));
            money.setStatus(rs.getInt("status"));
            return money;
        }
    }

}
